import {ActionSheet, Cell, Picker, TreeSelect} from "@antmjs/vantui";
import React, {ReactNode, useCallback, useEffect, useState} from "react";
import {View, Text} from "@tarojs/components";
import BottomButton from "@/components/bottom_button";
import AssetImage from "@/common/AssetImage";
import {SelectTimeModel} from "@/utils/date_utils";
import Utils from "@/utils/common";

export interface TimeSelectProps {
  items: SelectTimeModel[]
  max?: number
  title?: string
  text?: string | null
  initValue?: string
  initValues?: any[]
  renderTitle: ReactNode
  onComplete?: (values: any) => void;
  onBeforeOpen?: () => boolean;
}

export default function TimeSelect2(props: TimeSelectProps) {
  const [state, changeState] = useState({
    mainActiveIndex: 0,
    activeIds: props.initValues ? props.initValues : [],
  })

  const setState = (newState) => {
    changeState({
      ...state,
      ...newState,
    })
  }

  const onClickNav = ({detail = {}}) => {
    setState({
      mainActiveIndex: detail.index || 0,
    })
  }


  const onClickItem = ({detail = {}}) => {
    const activeIds = state.activeIds
    // 判断是否已经选中
    if (activeIds.includes(detail.id)) {
      activeIds.splice(activeIds.indexOf(detail.id), 1)
    } else {
      activeIds.push(detail.id)
    }
    setState({
      activeIds: [...activeIds],
    })
  }


  const [show, setShow] = useState(false)

  const handleCellClick = () => {
    let canOpen = true;
    if (props.onBeforeOpen) {
      canOpen = props.onBeforeOpen(); // Call the provided function
    }
    if (canOpen) {
      setShow(true);
    }
    // If canOpen is false, the function props.onBeforeOpen should handle any feedback (e.g., a toast)
  };

  useEffect(() => {
    let newActiveIds: any[] = [];
    if (props.initValues !== undefined) {
      newActiveIds = [...props.initValues]; // Create a new array
    } else if (props.initValue !== undefined) {
      newActiveIds = [props.initValue];
    }
    if (JSON.stringify(newActiveIds) !== JSON.stringify(state.activeIds)) {
      //activeIds为空时，初始化mainActiveIndex为0
      if (newActiveIds.length === 0) {
        setState({activeIds: newActiveIds, mainActiveIndex: 0});
      } else {
        setState({activeIds: newActiveIds});
      }
    }
  }, [props.initValues, props.initValue]);
  return (
    <View>
      <View>
        <Cell isLink renderIcon={props.title ? props.title : '请选择预约时间'}
              renderTitle={props.renderTitle} onClick={handleCellClick}
        />
      </View>
      <ActionSheet show={show} title={<View><Text>请选择预约时间</Text> <Text
        style={{color: 'green', fontSize: '14px'}}
      >{`已选择：${state.activeIds.length / 2}h`}</Text></View>}
                   onClose={() => setShow(false)} cancelText={
        <BottomButton submitText='选择完成' onSubmit={() => {
          if (state.activeIds.length < 1) {
            Utils.showErrorToast('最少预约0.5h')
            return
          }
          setShow(false)
          props.onComplete && props.onComplete(state.activeIds)
        }} margin='0px'
        />
      }
      >
        <View>
          <TreeSelect
            height='280px'
            items={props.items}
            mainActiveIndex={state.mainActiveIndex}
            activeId={state.activeIds}
            onClickNav={onClickNav}
            onClickItem={onClickItem}
            max={props.max ? props.max : 1}
          />
        </View>
      </ActionSheet>

    </View>
  );
}


export function TimeSelectSingle(pros: TimeSelectProps) {
  const [state, changeState] = useState({
    mainActiveIndex: 0,
    activeId: pros.initValue,
  })

  const setState = useCallback((newState) => {
    changeState({
      ...state,
      ...newState,
    })
  }, [state]);
  const onClickNav = ({detail = {}}) => {
    setState({
      mainActiveIndex: detail.index || 0,
    })
  }

  const onClickItem = ({detail = {}}) => {
    const activeId = state.activeId === detail.id ? null : detail.id
    setState({
      activeId,
    })
  }


  const [show, setShow] = useState(false)


  useEffect(() => {
    // 初始化时，如果value为空，则设置activeId为null
    setState({
      activeId: pros.initValue || null,
    });
  }, [pros.initValue, setState]);

  return (
    <View>
      <ActionSheet show={show} title='标题' onClose={() => setShow(false)} cancelText={
        <BottomButton submitText='确定' onSubmit={() => {
          setShow(false)
          pros.onComplete && pros.onComplete(state.activeId)
        }} margin='0px'
        />
      }
      >
        <View>
          <TreeSelect
            items={pros.items}
            mainActiveIndex={state.mainActiveIndex}
            activeId={state.activeId}
            onClickNav={onClickNav}
            onClickItem={onClickItem}
          />
        </View>
      </ActionSheet>
      <View style={{'--cell-value-color': pros.text ? 'black' : AssetImage.gray2}}>
        <Cell title={pros.title ? pros.title : '预约时间'}
              value={pros.text ? `${pros.text}` : '请选择'} onClick={() => {
          setShow(true)
        }}
        />
      </View>
    </View>
  );
}


export function TimeSelect3(pros: TimeSelectProps) {

  const getChildren = useCallback((index) => {
    if (pros.items[index] && pros.items[index].children) {
      return pros.items[index].children;
    }
    return [];
  }, [pros.items]);


  const [selectedResult, setSelectedResult] = useState<string[]>([]); // Stores the final confirmed text values

  const [pickerColumns, setPickerColumns] = useState(() => {
    const provinces = pros.items; // Format provinces for first column
    const initialCities = getChildren(0); // Format initial cities
    return [provinces, initialCities]; // Array of columns
  });


  const handlePickerChange = useCallback((event: any) => {
    const selectedIndices = event.detail.picker.getIndexes();
    const provinceIndex = selectedIndices[0] ?? 0; // Default to 0 if undefined
    const newCityOptions = getChildren(provinceIndex);
    setPickerColumns(prevColumns => [
      prevColumns[0],
      newCityOptions,
    ]);

  }, [getChildren]);

  const handleConfirm = (event: any) => {
    const selectedOptions = event.detail.picker.getValues(); // Get selected option objects
    const selectedText = selectedOptions.map(option => option.text); // Extract text
    setSelectedResult(selectedText); // Store the display text
  };

  return (
    <Picker
      showToolbar
      title='请选择预约时间'
      mode='content'
      idKey='id'
      value={selectedResult}
      columns={pickerColumns} // Pass the dynamic columns state here
      onChange={handlePickerChange} // Handle column changes for cascading
      onConfirm={handleConfirm} // Handle final confirmation
    />
  );
}






